<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="上级用户" prop="top">
        <el-input v-model="queryParams.top" placeholder="请输入上级用户" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['admin:user:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['admin:user:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['admin:user:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['admin:user:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-check" size="mini" @click="handleShowAudit" v-if="isAdmin"
          v-hasPermi="['admin:user:edit']">审核</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" row-key="id" default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="账号id" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="昵称" align="center" prop="nickname" />
      <el-table-column label="用户类型" align="center" prop="type">
        <template slot-scope="scope">
          <span v-if="scope.row.type === '0'">企业用户</span>
          <span v-if="scope.row.type === '1'">员工</span>
        </template>
      </el-table-column>
      <el-table-column label="所属企业" align="center" prop="top">
        <template slot-scope="scope">
          <span v-if="scope.row.top == 0">无</span>
          <!-- <span v-else-if="scope.row.top == bindUserId && !isAdmin">{{ nickName }}</span> -->
          <span v-else>
            <template v-for="item in topList">
              <span v-if="item.id == scope.row.top">{{ item.nickname }}</span>
            </template>
          </span>
          <!-- {{ scope.row.top }}</span> -->
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" prop="avatar">
        <template slot-scope="scope">
          <img :src="scope.row.avatar || defaultImage" alt="头像" style="width: 50px; height: 50px; border-radius: 50%;" />
        </template>
      </el-table-column>
      <el-table-column label="营业执照图片" align="center" prop="businessLicense" v-if="isAdmin">
        <template slot-scope="scope">
          <img :src="scope.row.businessLicense || defaultImage" alt="营业执照图片" style="width: 50px; height: 50px;" />
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="status" v-if="isAdmin">
        <template slot-scope="scope" v-if="scope.row.top == 0">
          <span v-if="scope.row.status == 0">待审核</span>
          <span v-if="scope.row.status == 1">审核通过</span>
          <span v-if="scope.row.status == 2">审核不通过</span>
        </template>
        <template slot-scope="scope" v-else>
          <span>-</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="是否删除" align="center" prop="isDel" >
        <template slot-scope="scope">
          <span v-if="scope.row.isDel === 0">否</span>
          <span v-if="scope.row.isDel === 1">是</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['admin:user:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-refresh" @click="rePassword(scope.row)"
            v-hasPermi="['admin:user:edit']">重置密码</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['admin:user:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" type="password" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="用户类型" prop="type" v-if="isAdmin">
          <el-select v-model="form.type" placeholder="请选择用户类型">
            <el-option label="企业" value="0" />
            <el-option label="员工" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="status" v-if="isAdmin && form.type == '0'">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="待审核" value="0" />
            <el-option label="审核通过" value="1" />
            <!-- <el-option label="审核不通过" value="2" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="上级用户" prop="top" v-if="isAdmin">
          <!-- <template v-if="nickname == 'admin'"> -->
          <el-select v-model="form.top" placeholder="请选择上级用户" :disabled="!isAdmin">
            <el-option v-for="item in topList" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
          <!-- </template> -->
          <!-- <template v-else>
            <el-input v-model="form.top" placeholder="请输入上级用户" aria-disabled="true" />
          </template>-->
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload action="http://localhost:8080/admin/user/upload"
            :class="{ 'hide': form.avatar != null && form.avatar != '' }" list-type="picture-card" :limit="1"
            :on-progress="(event, file) => handleProgress(event, file, 'avatar')"
            :on-preview="(file) => handlePictureCardPreview(file, 'avatar')"
            :on-success="(res, file) => handleAvatarSuccess(res, file, 'avatar')"
            :on-remove="(file, fileList) => handleRemove(file, fileList, 'avatar')">
            <img v-if="form.avatar" :src="form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicense" v-if="isAdmin">
          <el-upload action="http://localhost:8080/admin/user/upload"
            :class="{ 'hide': form.businessLicense != null && form.businessLicense != '' }" list-type="picture-card"
            :limit="1" :on-progress="(event, file) => handleProgress(event, file, 'businessLicense')"
            :on-preview="(file) => handlePictureCardPreview(file, 'businessLicense')"
            :on-success="(res, file) => handleAvatarSuccess(res, file, 'businessLicense')"
            :on-remove="(file, fileList) => handleRemove(file, fileList, 'businessLicense')">
            <img v-if="form.businessLicense" :src="form.businessLicense" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showImage" width="800px" append-to-body>
      <div>
        <img :src="showImageUrl" alt="头像" style="width: 100%; height: 100%;" />
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showAudit" width="800px" append-to-body>
      <div>
        <el-table :data="noAuditUserList" border>
          <el-table-column label="用户名" prop="username" />
          <el-table-column label="昵称" prop="nickname" />
          <el-table-column label="头像" prop="avatar">
            <template slot-scope="scope">
              <img :src="scope.row.avatar || defaultImage" alt="头像" @click="handleBusinessPreview(scope.row.avatar)" style="width: 50px; height: 50px; border-radius: 50%;" />
            </template>
          </el-table-column>
          <el-table-column label="营业执照" prop="businessLicense">
            <template slot-scope="scope">
              <img :src="scope.row.businessLicense || defaultImage" @click="handleBusinessPreview(scope.row.businessLicense)" alt="营业执照" style="width: 50px; height: 50px;" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-check" @click="handleAudit(scope.row,1)"
                v-hasPermi="['admin:user:edit']">审核通过</el-button>
              <el-button size="mini" type="text" icon="el-icon-close" @click="handleAudit(scope.row,2)"
                v-hasPermi="['admin:user:edit']">审核不通过</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showBusiness" width="800px" append-to-body>
      <div>
        <img :src="showBusinessUrl" alt="营业执照" style="width: 100%; height: 100%;" />
      </div>
    </el-dialog>
    <!-- <Rules :currentValue="60.5" /> -->
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import uploadMixin from '@/utils/upload'
import Rules from '@/components/Rules/Rules.vue'
import { listUser, getUser, delUser, addUser, updateUser, getNoAuditUser,resetPassword } from "@/api/admin/user"
import { handlePictureCardPreview, handleRemove, handleAvatarSuccess, handleProgress, handleBusinessPreview } from '@/utils/upload'
import { buildTree } from '@/utils/buildTree'

export default {
  name: "User",
  mixins: [uploadMixin],
  components: {
    Rules
  },
  computed: {
    ...mapGetters([
      'roles',
      'nickName',
      'bindUserId',
      'topUserList'
    ]),
    topList() {
      return this.topUserList
    },
    isAdmin() {
      return this.roles.includes('admin')
    }
  },
  data() {
    return {
      // 遮罩层
      showImage: false,
      showImageUrl: null,
      defaultImage: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        password: null,
        type: null,
        top: null,
        avatar: null,
        businessLicense: null,
        isDel: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
      },
      noAuditUserList:[],
      showAudit:false
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    console.log('this.bindUserId==>', this.bindUserId);

    // this.getList()
  },
  methods: {
    /** 查询用户列表 */
    async getList() {
      console.log('roles==>', this.roles)
      this.loading = true
      // if (this.isAdmin) {
        // const res = await selectUsersByTop()
        // console.log('res==>', res)
        // this.topList = res.data
      // }
      listUser(this.queryParams).then(response => {
        // console.log('构建后数据==>', buildTree(response.rows))
        // response.rows.forEach(item => {
        //   item.top = this.bindUserId ?? 0
        // })
        this.userList = buildTree(response.rows, this.bindUserId ?? 0)
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        username: '',
        password: '123456',
        type: null,
        top: null,
        avatar: null,
        status: '1',
        businessLicense: null,
        isDel: null,
        createTime: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.$set(this.form, 'top', this.bindUserId ?? null)
      this.$set(this.form, 'type', this.bindUserId == 0 ? '1' : '0')
      this.open = true
      this.title = "添加用户"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改用户"
      })
    },
    async handleShowAudit(){
      const list = await getNoAuditUser()
      this.noAuditUserList = list.data
      this.showAudit = true
    },
    async handleAudit(row,status){
      this.$set(this.form,'id',row.id)
      this.$set(this.form,'status',status)  
      updateUser(this.form).then(response => {
        this.$modal.msgSuccess("修改成功")
        // this.open = false
        this.handleShowAudit()
        this.getList()
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除用户编号为"' + ids + '"的数据项？').then(function () {
        return delUser(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('admin/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    rePassword(row){
      const id = row.id
      const username = row.username
      this.$modal.confirm('是否将用户'+username+"的密码设置为123456").then(()=>{
       return resetPassword(id)
      }).then(()=>{
        this.$modal.msgSuccess('修改成功')
      })
    }
  }
}
</script>

<style scoped>

</style>
